<template>
  <div>
    <!-- 搜索区（全局/多表共用） -->
    <div class="search-bar">
      <el-input v-model="search" placeholder="输入姓名/工号/部门等关键字搜索" class="mild-border-input" style="width: 260px;" clearable>
        <template #append>
          <el-button icon="el-icon-search" @click="fetchEmployeeList">搜索</el-button>
        </template>
      </el-input>
    </div>
    <div class="goods-archive">
      <!-- 操作栏 -->
      <div class="toolbar">
        <el-button type="primary" icon="el-icon-plus" @click="handleAddEmployee">新增员工</el-button>
        <el-button>删除</el-button>
        <el-button>批量设置</el-button>
        <el-dropdown>
          <el-button>启用 <i class="el-icon-arrow-down el-icon--right"></i></el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>启用</el-dropdown-item>
              <el-dropdown-item>停用</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button>导入</el-button>
      </div>
      <!-- 人员档案表格 -->
      <el-table
        :data="employeeList"
        border
        style="width: 100%; margin-top: 12px;"
        height="480"
        stripe
        :row-class-name="tableRowClassName"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column label="数据状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row['数据状态'] === '创建'" type="success">创建</el-tag>
            <el-tag v-else-if="scope.row['数据状态'] === '审核中'" type="warning">审核中</el-tag>
            <el-tag v-else-if="scope.row['数据状态'] === '已审核'" type="danger">已审核</el-tag>
            <el-tag v-else-if="scope.row['数据状态'] === '重新审核'" type="info">重新审核</el-tag>
            <el-tag v-else>{{ scope.row['数据状态'] || '-' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="员工工号" label="工号" width="100">
          <template #default="scope">
            <span v-if="scope.row['禁用状态'] === '已禁用'" style="text-decoration: line-through; color: #bbb;">{{ scope.row['员工工号'] }}</span>
            <span v-else>{{ scope.row['员工工号'] }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="员工姓名" label="姓名" width="120" />
        <el-table-column prop="性别" label="性别" width="60">
          <template #default="scope">
            <span>{{ scope.row['性别'] === '1' ? '女' : scope.row['性别'] === '0' ? '男' : scope.row['性别'] }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="在职状态" label="在职状态" width="100" />
        <el-table-column prop="部门全称" label="部门" width="120" />
        <el-table-column prop="移动电话" label="手机号" width="120" />
        <el-table-column prop="电子邮箱" label="邮箱" width="160" />
        <el-table-column prop="身份证" label="身份证" width="160" />
        <el-table-column prop="入职日期" label="入职日期" width="120">
          <template #default="scope">
            <span>{{ scope.row['入职日期'] ? scope.row['入职日期'].substring(0, 10) : '' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="合同到期" label="合同到期" width="120">
          <template #default="scope">
            <span>{{ scope.row['合同到期'] ? scope.row['合同到期'].substring(0, 10) : '' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="描述" label="描述" width="120" />
        <!-- 新增操作列 -->
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="scope">
            <el-button type="primary" link size="small" @click="handleEdit(scope.row)">修改</el-button>
            <el-button type="primary" link size="small" @click="handleApprove(scope.row)">审批</el-button>
            <el-button type="danger" link size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination-bar">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="employeeTotal"
          :page-size="pageSize"
          :current-page="currentPage"
          :page-sizes="[20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router'; // 新增
import { employeeArchiveQuery, deleteEmployee } from '@/api/api';
import { ElMessageBox, ElMessage } from 'element-plus';
const search = ref('');
const currentPage = ref(1);
const pageSize = ref(20);
const employeeList = ref([]);
const employeeTotal = ref(0);
const selectedRows = ref([]); // 新增：用于存储选中的行
const router = useRouter(); // 新增

// 批量选择回调
function handleSelectionChange(val) {
  selectedRows.value = val;
}

// 请求人员档案数据
async function fetchEmployeeList() {
  try {
    const params = {
      p: { page_number: currentPage.value, page_size: pageSize.value },
      e: { where: true, fid: search.value }
    }
    const res = await employeeArchiveQuery(params);
    if (Array.isArray(res?.data?.data)) {
      employeeList.value = res.data.data;
      employeeTotal.value = res.data.total || res.data.data.length;
    } else if (Array.isArray(res?.data)) {
      employeeList.value = res.data;
      employeeTotal.value = res.data.length;
    } else {
      employeeList.value = [];
      employeeTotal.value = 0;
    }
  } catch (e) {
    employeeList.value = [];
    employeeTotal.value = 0;
  }
}

function handleSizeChange(size) {
  pageSize.value = size;
  fetchEmployeeList();
}
function handleCurrentChange(page) {
  currentPage.value = page;
  fetchEmployeeList();
}

onMounted(() => {
  fetchEmployeeList();
});
function handleEdit(row) {
  // 存储数据到 sessionStorage
  sessionStorage.setItem('editEmployeeData', JSON.stringify(row));
  router.push({
    path: '/adminAuth/adminList',
    query: { type: 'edit', fid: row['FID'] || row['主键ID'] || row['id'] }
  });
}
function handleApprove(row) {
  // TODO: 审批逻辑
  console.log('审批', row);
}
function handleDelete(row) {
  const code = row['员工工号'] || row['员工编号'] || row['工号'] || row['编码'] || row['number'];
  const name = row['员工姓名'] || row['姓名'] || row['name'] || '';
  if (!code) {
    ElMessage.error('未获取到员工工号，无法删除');
    return;
  }
  ElMessageBox.confirm(
    `确定要删除员工【${name}】（工号：${code}）吗？`,
    '提示',
    { type: 'warning' }
  ).then(async () => {
    try {
      const res = await deleteEmployee({ number: [code] });
      if (res.data.code === 200) {
        ElMessage.success('删除成功');
        fetchEmployeeList();
      } else {
        // 优化：后端返回的 Message 字段优先弹窗提示
        const msg = res.data?.data?.[0]?.Message || res.data.msg || '删除失败';
        ElMessage.error(msg);
      }
    } catch (e) {
      ElMessage.error('请求失败');
    }
  }).catch(() => {
    // 用户取消
  });
}
function handleAddEmployee() {
  router.push({
    path: '/adminAuth/adminList',
    query: { type: 'add' }
  });
}
// 行样式：禁用状态为已禁用时整行加横线
function tableRowClassName({ row }) {
  return row['禁用状态'] === '已禁用' ? 'row-disabled' : '';
}
</script>

<style scoped>
.goods-archive {
  background: #fff;
  border-radius: 8px;
  padding: 24px;
  border: 1.5px solid #bfc6d1;
}
.search-bar {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  padding-bottom: 4px;
  border-bottom: 1px solid #e5e6eb;
  background: #f8f9fb;
  border-radius: 6px;
  padding: 12px 12px 8px 12px;
}
.toolbar {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 8px;
}
.pagination-bar {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
/* 较浅的边框输入框样式 */
.mild-border-input :deep(.el-input__inner),
.mild-border-input :deep(.el-select__wrapper) {
  /* border: 1.5px solid #bfc6d1 !important; */
  box-shadow: none !important;
  background: #fff;
}

/* 表格行颜色美化 */
:deep(.el-table__body tr.custom-row) {
  background-color: #f4f6fa;
  transition: background 0.2s;
}
:deep(.el-table__body tr.custom-row:nth-child(even)) {
  background-color: #e9edf5;
}
:deep(.el-table__body tr.custom-row:hover) {
  background-color: #dbe3f3 !important;
}
:deep(.row-disabled) td {
  text-decoration: line-through;
  color: #bbb !important;
}
</style>
